﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;

namespace RG.Common
{
    public static class SerializeAndBackExtension
    {
        public static T SerializeAndBack<T>(this T obj)
        {
            var serializer = new DataContractSerializer(typeof(T));

            using (var f = new MemoryStream())
            {
                serializer.WriteObject(f, obj);
                f.Seek(0, SeekOrigin.Begin);
                return (T)serializer.ReadObject(f);
            }
        }

        public static string ToWcfString(this object obj, bool OmitXmlDeclaration = false)
        {
            var serializer = new DataContractSerializer(obj.GetType());
            var sb = new StringBuilder();
            using (var writer = XmlWriter.Create(sb, new XmlWriterSettings { Indent = false, OmitXmlDeclaration = OmitXmlDeclaration }))
            {
                if (writer == null) throw new ApplicationException("Writer обломился");
                serializer.WriteObject(writer, obj);
            }
            return sb.ToString();
        }

        public static object FromWcfString(this Type objType, string wcfString)
        {
            var serializer = new DataContractSerializer(objType);
            using (var reader = new XmlTextReader(new StringReader(wcfString)))
            {
                return serializer.ReadObject(reader);
            }
        }

        public static T FromWcfString<T>(this string wcfString)
        {
            var serializer = new DataContractSerializer(typeof(T));
            using (var reader = new XmlTextReader(new StringReader(wcfString)))
            {
                return (T)serializer.ReadObject(reader);
            }
        }

        public static object FromWcfString (this string wcfString, Type T)
        {
            var serializer = new DataContractSerializer(T);
            using (var reader = new XmlTextReader(new StringReader(wcfString)))
            {
                return serializer.ReadObject(reader);
            }
        }

    }
}
